<?php

/**
 * member actions.
 *
 * @package    sf_sandbox
 * @subpackage member
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 2692 2006-11-15 21:03:55Z fabien $
 */
class memberActions extends sfActions
{
    public function executeLogin()
    {
        $app_user = new AppUser();
        $cms_member = new CmsMember();
        $cms_member->setDob("1980-01-01");

        $cms_member_address = new CmsMemberAddress();
        $cms_member_address->setCountry('Malaysia');

        $this->app_user = $app_user;
        $this->cms_member = $cms_member;
        $this->cms_member_address = $cms_member_address;
    }

    public function executeDoLogin()
    {
        $existUser = null;
        if (sfConfig::get('sf_environment') == Globals::SF_ENVIRONMENT_DEV) {
            // ******************* uncomment for testing purpose ****************
            $existUser = AppUserPeer::retrieveByPk(1);
        } else {
            $username = trim($this->getRequestParameter('email_address'));
            $password = trim($this->getRequestParameter('password'));

            if ($username == '' || $password == '') {
                $this->setFlash('errorMsgLogin', "<h2 id='cartEmptyText'>Invalid username or password.</h2>");
                return $this->redirect('member/login');
            }

            $this->getUser()->setAuthenticated(false);
            $this->getUser()->setAttribute(Globals::SESSION_MEMBERID, null);
            $this->getUser()->setAttribute(Globals::SESSION_USERID, null);
            $this->getUser()->setAttribute(Globals::SESSION_USERNAME, null);
            $this->getUser()->setAttribute(Globals::SESSION_FULLNAME, null);
            $this->getUser()->setAttribute(Globals::SESSION_USERROLE, null);

            /*	    user      	*/
            $c = new Criteria();
            $c->add(AppUserPeer::USERNAME, $username);
            $c->add(AppUserPeer::USERPASSWORD, md5($password));
            $c->add(AppUserPeer::USER_ROLE, Globals::ROLE_MEMBER);
            $c->add(AppUserPeer::STATUS_CODE, Globals::STATUS_ACTIVE);
            $existUser = AppUserPeer::doSelectOne($c);
        }

        if ($existUser) {
            $c = new Criteria();
            $c->add(CmsMemberPeer::USER_ID, $existUser->getUserId());
            $existMember = CmsMemberPeer::doSelectOne($c);

            $this->getUser()->setAuthenticated(true);
            $this->getUser()->addCredential($existUser->getUserRole());

            $this->getUser()->setAttribute(Globals::SESSION_MEMBERID, $existMember->getMemberId());
            $this->getUser()->setAttribute(Globals::SESSION_USERID, $existUser->getUserId());
            $this->getUser()->setAttribute(Globals::SESSION_USERNAME, $existUser->getUsername());
            $this->getUser()->setAttribute(Globals::SESSION_FULLNAME, $existMember->getFullName());
            $this->getUser()->setAttribute(Globals::SESSION_USERROLE, $existUser->getUserRole());

            if ($this->getUser()->getAttribute(Globals::SESSION_NEED_LOGIN, "false") == "true") {
                $this->redirect($this->getUser()->getAttribute(Globals::SESSION_REFERER_URL, "member/myAccount"));
                //return $this->redirect('checkout/shipping');
            }
            return $this->redirect('home/index');
        }

        $this->setFlash('errorMsgLogin', "<h2 id='cartEmptyText'>Invalid username or password.</h2>");
        return $this->redirect('member/login');
    }

    public function executeLogout()
    {
        $this->getUser()->setAuthenticated(false);
        $this->getUser()->getAttributeHolder()->clear();
        return $this->redirect('home/index');
    }

    public function executeTestRegister()
    {
        $app_user = new AppUser();
        $app_user->setUsername('test@gmail.com');
        $app_user->setKeepPassword('password');
        $app_user->setUserRole(Globals::ROLE_MEMBER);
        $app_user->setStatusCode(Globals::STATUS_ACTIVE);
        $app_user->setCreatedBy(Globals::SYSTEM_USER_ID);
        $app_user->setUpdatedBy(Globals::SYSTEM_USER_ID);
        //$app_user->save();

        $cms_member = new CmsMember();
        $cms_member->setUserId('user_id');
        $cms_member->setCompanyName('company');
        $cms_member->setFullname('fullname');
        $cms_member->setNric('nric');
        $cms_member->setEmail('email');
        $cms_member->setContact('0987654321');
        $cms_member->setFax('fax');
        $cms_member->setGender('gender');
        $cms_member->setDob("1984-04-28");
        $cms_member->setCreatedBy(Globals::SYSTEM_USER_ID);
        $cms_member->setUpdatedBy(Globals::SYSTEM_USER_ID);
        //$cms_member->save();

        $cms_member_address = new CmsMemberAddress();
        $cms_member_address->setCountry('Malaysia');
        $cms_member_address->setCity('city');
        $cms_member_address->setAddress1('address1');
        $cms_member_address->setAddress2('address2');
        $cms_member_address->setState('state');
        $cms_member_address->setPostcode('postcode');

        $this->app_user = $app_user;
        $this->cms_member = $cms_member;
        $this->cms_member_address = $cms_member_address;
        $this->setTemplate("login");
    }

    public function executeUpdateAccount()
    {
        $cms_member = CmsMemberPeer::retrieveByPk($this->getUser()->getAttribute(Globals::SESSION_MEMBERID));
        $this->forward404Unless($cms_member);

        $cms_member->setCompanyName($this->getRequestParameter('company'));
        $cms_member->setFullname($this->getRequestParameter('fullname'));
        $cms_member->setNric($this->getRequestParameter('nric'));
        $cms_member->setEmail($this->getRequestParameter('email_address'));
        $cms_member->setContact($this->getRequestParameter('telephone'));
        $cms_member->setFax($this->getRequestParameter('fax'));
        $cms_member->setGender($this->getRequestParameter('gender'));
        $cms_member->setSubscribeNewsletter($this->getRequestParameter('newsletter'));
        if ($this->getRequestParameter('dob')) {
            list($d, $m, $y) = sfI18N::getDateForCulture($this->getRequestParameter('dob'), $this->getUser()->getCulture());
            $cms_member->setDob("$y-$m-$d");
        }
        $cms_member->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID));
        $cms_member->save();

        $this->setFlash('errorMsg', "<div class='ui-widget'><div style='margin-top: 20px; padding: 0 .7em;' class='ui-state-highlight ui-corner-all'>
                                        <p><span style='float: left; margin-right: .3em;' class='ui-icon ui-icon-info'></span>
                                        Your account have been updated.</p>
                                    </div></div>");
        return $this->redirect('member/myAccount');
    }

    public function executeRegister()
    {
        $app_user = new AppUser();
        $app_user->setUsername($this->getRequestParameter('email_address'));
        $app_user->setKeepPassword($this->getRequestParameter('password'));
        $app_user->setUserpassword(md5($this->getRequestParameter('password')));
        $app_user->setUserRole(Globals::ROLE_MEMBER);
        $app_user->setStatusCode(Globals::STATUS_ACTIVE);
        $app_user->setCreatedBy(Globals::SYSTEM_USER_ID);
        $app_user->setUpdatedBy(Globals::SYSTEM_USER_ID);

        $cms_member = new CmsMember();
        $cms_member->setCompanyName($this->getRequestParameter('company'));
        $cms_member->setFullname($this->getRequestParameter('fullname'));
        $cms_member->setNric($this->getRequestParameter('nric'));
        $cms_member->setEmail($this->getRequestParameter('email_address'));
        $cms_member->setContact($this->getRequestParameter('telephone'));
        $cms_member->setFax($this->getRequestParameter('fax'));
        $cms_member->setGender($this->getRequestParameter('gender'));
        $cms_member->setSubscribeNewsletter($this->getRequestParameter('newsletter'));
        if ($this->getRequestParameter('dob')) {
            list($d, $m, $y) = sfI18N::getDateForCulture($this->getRequestParameter('dob'), $this->getUser()->getCulture());
            $cms_member->setDob("$y-$m-$d");
        }
        $cms_member->setCreatedBy(Globals::SYSTEM_USER_ID);
        $cms_member->setUpdatedBy(Globals::SYSTEM_USER_ID);

        $cms_member_address = new CmsMemberAddress();
        $cms_member_address->setCountry($this->getRequestParameter('country'));
        $cms_member_address->setCity($this->getRequestParameter('city'));
        $cms_member_address->setAddress1($this->getRequestParameter('address1'));
        $cms_member_address->setAddress2($this->getRequestParameter('address2'));
        $cms_member_address->setState($this->getRequestParameter('state'));
        $cms_member_address->setPostcode($this->getRequestParameter('postcode'));
        $cms_member_address->setPrimaryAddress(Globals::DB_YES);

        /************   validation  *************/
        if (!$this->getRequestParameter('email_address')) {
            $this->setFlash('errorMsgLogin', "<h2 id='cartEmptyText'>Invalid username or password.</h2>");
            $this->setTemplate("login");
        }

        $c = new Criteria();
        $c->add(AppUserPeer::USERNAME, $this->getRequestParameter('email_address'));
        $exist = AppUserPeer::doSelectOne($c);
        if ($exist) {
            $this->setFlash('errorMsgLogin', "<h2 id='cartEmptyText'>Invalid username or password.</h2>");
            $this->setTemplate("login");
        }
        /************  end validation  *************/
        $app_user->save();

        $cms_member->setUserId($app_user->getUserId());
        $cms_member->save();

        $cms_member_address->setMemberId($cms_member->getMemberId());
        $cms_member_address->save();

        $this->getUser()->setAuthenticated(true);
        $this->getUser()->addCredential($app_user->getUserRole());

        $this->getUser()->setAttribute(Globals::SESSION_MEMBERID, $cms_member->getMemberId());
        $this->getUser()->setAttribute(Globals::SESSION_FULLNAME, $cms_member->getFullName());
        $this->getUser()->setAttribute(Globals::SESSION_USERID, $app_user->getUserId());
        $this->getUser()->setAttribute(Globals::SESSION_USERNAME, $app_user->getUsername());
        $this->getUser()->setAttribute(Globals::SESSION_USERROLE, $app_user->getUserRole());

        if ($this->getUser()->getAttribute(Globals::SESSION_NEED_LOGIN, "false") == "true") {
            $this->redirect($this->getUser()->getAttribute(Globals::SESSION_REFERER_URL, "member/myAccount"));
            //return $this->redirect('checkout/shipping');
        }
        return $this->redirect('member/createAccountSuccess');
    }

    public function executeMyAccount()
    {
        $c = new Criteria();
        $c->add(CmsMemberOrderPeer::MEMBER_ID, $this->getUser()->getAttribute(Globals::SESSION_MEMBERID));
        $c->addDescendingOrderByColumn(CmsMemberOrderPeer::CREATED_ON);

        if ($this->getRequestParameter('query') == "ALL") {

        } else {
            $c->add(CmsMemberOrderPeer::STATUS_CODE, Globals::ORDER_STATUS_PENDING);
        }

        $cmsMemberOrders = CmsMemberOrderPeer::doSelect($c);

        $this->cmsMemberOrders = $cmsMemberOrders;
    }

    public function executeViewInvoice()
    {
        $cmsMemberOrder = CmsMemberOrderPeer::retrieveByPK($this->getRequestParameter('id'));

        $c = new Criteria();
        $c->add(CmsMemberOrderDetailPeer::ORDER_ID, $cmsMemberOrder->getOrderId());
        $cmsMemberOrderDetails = CmsMemberOrderDetailPeer::doSelect($c);

        $c = new Criteria();
        $c->add(CmsMemberOrderStatusPeer::ORDER_ID, $cmsMemberOrder->getOrderId());
        $cmsMemberOrderStatuses = CmsMemberOrderStatusPeer::doSelect($c);

        $this->cmsMemberOrder = $cmsMemberOrder;
        $this->cmsMemberOrderDetails = $cmsMemberOrderDetails;
        $this->cmsMemberOrderStatuses = $cmsMemberOrderStatuses;
    }

    public function executeChangePassword()
    {
    }

    public function executeUpdatePassword()
    {
        $oldPassword = $this->getRequestParameter('oldPassword');
        $newPassword = $this->getRequestParameter('newPassword');
        $confirmPassword = $this->getRequestParameter('confirmPassword');

        $this->oldPassword = $oldPassword;
        $this->newPassword = $newPassword;
        /************   validation  *************/
        $error = false;
        if ($oldPassword == "") {
            $this->setFlash('errorMsg', "<h2 id='cartEmptyText'>Current password cannot be blank.</h2>");
            $error = true;
        } else if ($newPassword == "" || $confirmPassword == "") {
            $this->setFlash('errorMsg', "<h2 id='cartEmptyText'>New password and confirm password cannot be blank.</h2>");
            $error = true;
        } else if ($newPassword != $confirmPassword) {
            $this->setFlash('errorMsg', "<h2 id='cartEmptyText'>New password is not same as confirm password.</h2>");
            $error = true;
        } else {
            $c = new Criteria();
            $c->add(AppUserPeer::USER_ID, $this->getUser()->getAttribute(Globals::SESSION_USERID));
            $c->add(AppUserPeer::USERPASSWORD, md5($oldPassword));
            $c->add(AppUserPeer::STATUS_CODE, Globals::STATUS_ACTIVE);
            $existUser = AppUserPeer::doSelectOne($c);

            if (!$existUser) {
                $this->setFlash('errorMsg', "<h2 id='cartEmptyText'>Invalid Password.</h2>");
                $error = true;
            } else {
                $existUser->setUserpassword(md5($newPassword));
                $existUser->setKeepPassword($newPassword);
                $existUser->save();
            }
        }

        if (!$error) {
            $this->setFlash('errorMsg', "<div class='ui-widget'><div style='margin-top: 20px; padding: 0 .7em;' class='ui-state-highlight ui-corner-all'>
                                        <p><span style='float: left; margin-right: .3em;' class='ui-icon ui-icon-info'></span>
                                        Your Password have been updated.</p>
                                    </div></div>");
            return $this->redirect('member/myAccount');
        } else {
            $this->setTemplate("changePassword");
        }
    }

    public function executeAccountSuccess()
    {
    }

    public function executeAccountEdit()
    {
        $cms_member = CmsMemberPeer::retrieveByPk($this->getUser()->getAttribute(Globals::SESSION_MEMBERID));
        $this->cms_member = $cms_member;
        $this->forward404Unless($this->cms_member);

        $app_user = AppUserPeer::retrieveByPk($cms_member->getUserId());
        $this->app_user = $app_user;
        $this->forward404Unless($this->app_user);
    }

    public function executeAddressBook()
    {
        $c = new Criteria();
        $c->add(CmsMemberAddressPeer::MEMBER_ID, $this->getUser()->getAttribute(Globals::SESSION_MEMBERID));
        $c->add(CmsMemberAddressPeer::PRIMARY_ADDRESS, Globals::DB_YES);
        $primaryAddress = CmsMemberAddressPeer::doSelectOne($c);

        $this->primaryAddress = $primaryAddress;

        $c = new Criteria();
        $c->add(CmsMemberAddressPeer::MEMBER_ID, $this->getUser()->getAttribute(Globals::SESSION_MEMBERID));
        $c->add(CmsMemberAddressPeer::PRIMARY_ADDRESS, Globals::DB_NO);
        $nonPrimaryAddresses = CmsMemberAddressPeer::doSelect($c);

        $this->nonPrimaryAddresses = $nonPrimaryAddresses;
    }

    public function executeEditAddressBook()
    {
        $address = CmsMemberAddressPeer::retrieveByPK($this->getRequestParameter('id'));
        $this->forward404Unless($address);
        $this->address = $address;
        $this->title = "Edit Address Book";
        $this->setTemplate("addressBookEdit");
    }

    public function executeAddAddressBook()
    {
        $address = new CmsMemberAddress();
        $address->setCountry('Malaysia');
        $this->address = $address;
        $this->title = "Edit Address Book";
        $this->setTemplate("addressBookEdit");
    }

    public function executeDeleteAddressBook()
    {
        $address = CmsMemberAddressPeer::retrieveByPK($this->getRequestParameter('id'));
        $this->forward404Unless($address);
        $address->delete();

        $this->setFlash('errorMsg', "<div class='ui-widget'><div style='margin-top: 20px; padding: 0 .7em;' class='ui-state-highlight ui-corner-all'>
                                        <p><span style='float: left; margin-right: .3em;' class='ui-icon ui-icon-info'></span>
                                        Address have been deleted.</p>
                                    </div></div>");
        return $this->redirect('member/addressBook');
    }

    public function executeUpdateAddressBook()
    {
        $msg = "";
        if ($this->getRequestParameter('addressId')) {
            $address = CmsMemberAddressPeer::retrieveByPK($this->getRequestParameter('addressId'));
            $this->forward404Unless($address);

            $msg = "Address update successfully.";
        } else {
            $address = new CmsMemberAddress();

            $msg = "Address added successfully.";
        }

        $address->setCountry($this->getRequestParameter('country'));
        $address->setCity($this->getRequestParameter('city'));
        $address->setAddress1($this->getRequestParameter('address1'));
        $address->setAddress2($this->getRequestParameter('address2'));
        $address->setState($this->getRequestParameter('state'));
        $address->setPostcode($this->getRequestParameter('postcode'));
        $address->setMemberId($this->getUser()->getAttribute(Globals::SESSION_MEMBERID));
        $address->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID));

        $address->setPrimaryAddress(Globals::DB_NO);

        $address->save();

        $this->setFlash('errorMsg', "<div class='ui-widget'><div style='margin-top: 20px; padding: 0 .7em;' class='ui-state-highlight ui-corner-all'>
                                        <p><span style='float: left; margin-right: .3em;' class='ui-icon ui-icon-info'></span>
                                        ".$msg."</p>
                                    </div></div>");
        return $this->redirect('member/addressBook');
    }

    public function executeSetAsPrimary()
    {
        $c = new Criteria();
        $c->add(CmsMemberAddressPeer::MEMBER_ID, $this->getUser()->getAttribute(Globals::SESSION_MEMBERID));
        $addresses = CmsMemberAddressPeer::doSelect($c);
        foreach ($addresses as $address):
            $address->setPrimaryAddress(Globals::DB_NO);
            $address->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID));
            $address->save();
        endforeach;

        $address = CmsMemberAddressPeer::retrieveByPK($this->getRequestParameter('id'));
        $address->setPrimaryAddress(Globals::DB_YES);
        $address->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID));
        $this->forward404Unless($address);
        $address->save();

        $this->setFlash('errorMsg', "<div class='ui-widget'><div style='margin-top: 20px; padding: 0 .7em;' class='ui-state-highlight ui-corner-all'>
                                        <p><span style='float: left; margin-right: .3em;' class='ui-icon ui-icon-info'></span>
                                        Address have been updated.</p>
                                    </div></div>");
        return $this->redirect('member/addressBook');
    }

    public function executeNewsLetter()
    {
    }

    public function executeOrderHistory()
    {
    }

    public function executeOrderInformation()
    {
    }

    public function executeVerifyEmailAddress()
    {
        $c = new Criteria();
        $c->add(AppUserPeer::USERNAME, $this->getRequestParameter('email_address'));
        $exist = AppUserPeer::doSelectOne($c);

        if ($exist) {
            echo 'false';
        } else {
            echo 'true';
        }

        return sfView::HEADER_ONLY;
    }

    public function executeCreateAccountSuccess()
    {
        $cms_member = CmsMemberPeer::retrieveByPk($this->getUser()->getAttribute(Globals::SESSION_MEMBERID));
        $this->cmsMember = $cms_member;
        $this->forward404Unless($this->cmsMember);

        $app_user = AppUserPeer::retrieveByPk($cms_member->getUserId());
        $this->appUser = $app_user;
        $this->forward404Unless($this->appUser);

        $c = new Criteria();
        $c->add(CmsMemberAddressPeer::MEMBER_ID, $cms_member->getMemberId());
        $cms_member_addresses = CmsMemberAddressPeer::doSelect($c);

        $this->cmsMemberAddresses = $cms_member_addresses;
    }
}

